//
//  PassCodeViewController.m
//  iEPD
//
//  Created by ENVANG on 1/2/13.
//  Copyright (c) 2013 Mobioneer Ltd. All rights reserved.
//


#import "PassCodeViewController.h"
#import "SettingsViewController.h"
#import <QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"

@interface PassCodeViewController ()

@end

@implementation PassCodeViewController
@dynamic window;
@synthesize animationView;

@synthesize titleLabel;
@synthesize instructionLabel;

@synthesize bulletField0;
@synthesize bulletField1;
@synthesize bulletField2;
@synthesize bulletField3;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];
    
    self.passnhap = @"";
    self.d = 0;
    fakeField = [[UITextField alloc] initWithFrame:CGRectZero];
    fakeField.delegate = self;
    fakeField.keyboardType = UIKeyboardTypeNumberPad;
    fakeField.secureTextEntry = YES;
    fakeField.text = @"";
    [fakeField becomeFirstResponder];
    [self.view addSubview:fakeField];
    NSUserDefaults * config = [NSUserDefaults standardUserDefaults];
    if ([@"changepass" isEqualToString:[config objectForKey:@"_changePass_"]]) {
        self.navigationItem.title = NSLocalizedString(@"ChangPasscode", @"");
        self.titleLabel.text = NSLocalizedString(@"EnterYourOldPasscode",@"");
        self.instructionLabel.text = @"";
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonSystemItemCancel target:self action:@selector(cancelChangePass)];
    }
    else if (![@"FIRSTUSER" isEqualToString:[config objectForKey:@"_key_"]]) {
        self.navigationItem.title = NSLocalizedString(@"SetPasscode", @"");
    }
    else{
        self.navigationItem.title = NSLocalizedString(@"EnterPasscode", @"");
        self.titleLabel.text = @"";
    }
}

- (void)viewDidUnload {
    
    [super viewDidUnload];
    fakeField = nil;
    self.animationView = nil;
    
    self.titleLabel = nil;
    self.instructionLabel = nil;
    
    self.bulletField0 = nil;
    self.bulletField1 = nil;
    self.bulletField2 = nil;
    self.bulletField3 = nil;
    
}

- (void)cancelChangePass{
    
    NSUserDefaults * config = [NSUserDefaults standardUserDefaults];
    [config setObject:@"" forKey:@"_changePass_"];
    [config setObject:@"" forKey:@"_pass_"];
    [config synchronize];
    [self dismissModalViewControllerAnimated:YES];
    
}

#pragma mark - CAAnimationDelegate

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    
    self.bulletField0.text = nil;
    self.bulletField1.text = nil;
    self.bulletField2.text = nil;
    self.bulletField3.text = nil;
    fakeField.text = @"";
    
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *passcode = [textField text];
    passcode = [passcode stringByReplacingCharactersInRange:range withString:string];
    switch ([passcode length]) {
        case 0:
            self.bulletField0.text = nil;
            self.bulletField1.text = nil;
            self.bulletField2.text = nil;
            self.bulletField3.text = nil;
            break;
        case 1:
            self.bulletField0.text = @"*";
            self.bulletField1.text = nil;
            self.bulletField2.text = nil;
            self.bulletField3.text = nil;
            break;
        case 2:
            self.bulletField0.text = @"*";
            self.bulletField1.text = @"*";
            self.bulletField2.text = nil;
            self.bulletField3.text = nil;
            break;
        case 3:
            self.bulletField0.text = @"*";
            self.bulletField1.text = @"*";
            self.bulletField2.text = @"*";
            self.bulletField3.text = nil;
            break;
        case 4:
            self.bulletField0.text = @"*";
            self.bulletField1.text = @"*";
            self.bulletField2.text = @"*";
            self.bulletField3.text = @"*";
            break;
            
        default:
            break;
    }
    NSString *pass = passcode;
    if ([passcode length] == 4 ){
        self.d++;
        //NSLog(@"gia tri d= %d",self.d);
        NSUserDefaults * config = [NSUserDefaults standardUserDefaults];
        if (![@"HOME" isEqualToString:[config objectForKey:@"_homeChangePass_"]]) {
            
            if ([@"changepass" isEqualToString:[config objectForKey:@"_changePass_"]]) {
                [self performSelector:@selector(checkOldPass:) withObject:pass afterDelay:0.3];
            }
            else if ([@"1" isEqualToString:[config objectForKey:@"_changePass_"]]) {
                    if ([pass isEqualToString:[config objectForKey:@"_passCode_"]]) {
                        self.titleLabel.text = NSLocalizedString(@"EnterYourNewPasscode",@"");
                        self.instructionLabel.text = NSLocalizedString(@"EnterDifferentPasscode",@"");
                        [  self performSelector:@selector(interface)];
                    }
                    else{
                        self.titleLabel.text = NSLocalizedString(@"ReEnterYourNewPasscode",@"");
                        self.instructionLabel.text = @"";
                        [config setObject:pass forKey:@"_pass_"];
                        [config setObject:@"2" forKey:@"_changePass_"];
                        [config synchronize];
                        [self performSelector:@selector(interface)];
                    }
            }
            else if([@"2" isEqualToString:[config objectForKey:@"_changePass_"]]){
                    [self performSelector:@selector(changePass:) withObject:pass afterDelay:0.3];
            }
            else if (![@"FIRSTUSER" isEqualToString:[config objectForKey:@"_key_"]]) {
                    [self performSelector:@selector(endPass:) withObject:pass afterDelay:0.3];
            }
            else{
                [self performSelector:@selector(checkLogin:) withObject:pass afterDelay:0.3];
            }
        }
        else{
            [self performSelector:@selector(checkLogin:) withObject:pass afterDelay:0.3];
        }
        if (self.d == 1) {
            self.passnhap = pass;
        }
    }
       
    return [passcode length] <= 4;
}

#pragma mark - changePassCode

- (void)changePass:(NSString *)pass{
    
    NSUserDefaults * config = [NSUserDefaults standardUserDefaults];
    if ([pass isEqualToString:[config objectForKey:@"_pass_"]]){
        [config setObject:pass forKey:@"_passCode_"];
        [config setObject:@"" forKey:@"_changePass_"];
        [config setObject:@"" forKey:@"_pass_"];
        [config synchronize];
        self.d = 0;
        [self dismissModalViewControllerAnimated:YES];
    }
    else{
        self.titleLabel.text = NSLocalizedString(@"EnterYourNewPasscode",@"");
        self.instructionLabel.text = NSLocalizedString(@"PasscodeDidNotMatch",@"");
        [config setObject:@"1" forKey:@"_changePass_"];
        [config setObject:@""  forKey:@"_pass_"];
        [self performSelector:@selector(interface)];
    }
}

- (void)checkOldPass:(NSString *)pass{
    
    NSUserDefaults * config = [NSUserDefaults standardUserDefaults];
    if ([pass isEqualToString:[config objectForKey:@"_passCode_"]]) {
        self.titleLabel.text = NSLocalizedString(@"EnterYourNewPasscode",@"");
        self.instructionLabel.text = @"";
        [config setObject:@"1" forKey:@"_changePass_"];
        [config synchronize];
        [self performSelector:@selector(interface)];
    }
    else{
        self.titleLabel.text = NSLocalizedString(@"EnterYourOldPasscode",@"");
        self.instructionLabel.text =NSLocalizedString(@"WrongPasscode",@"");
        [self performSelector:@selector(interface)];
    }
}

- (void)checkLogin:(NSString *)pass{
    
    NSUserDefaults * config = [NSUserDefaults standardUserDefaults];
    if ([pass isEqualToString:[config objectForKey:@"_passCode_"]]) {
        [self dismissModalViewControllerAnimated:YES];
        [config setObject:@"" forKey:@"_homeChangePass_"];
        [config synchronize];
    }
    else{
        self.titleLabel.text = @"";
        self.instructionLabel.text = NSLocalizedString(@"WrongPasscode",@"");
        [self performSelector:@selector(interface)];
    }
}

- (void)interface{
    
    self.bulletField0.text = nil;
    self.bulletField1.text = nil;
    self.bulletField2.text = nil;
    self.bulletField3.text = nil;
    
    CATransition *transition = [CATransition animation];
    [transition setDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:)];
    [transition setType:kCATransitionPush];
    [transition setSubtype:kCATransitionFromRight];
    [transition setDuration:0.5f];
    [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    [[animationView layer] addAnimation:transition forKey:@"swipe"];
}

- (void)endPass:(NSString *)pass{
    
    self.titleLabel.text = NSLocalizedString(@"ReEnterYourPasscode", @"");
    self.instructionLabel.text = @"";
    [self performSelector:@selector(interface)];
    if (self.d == 2){
         self.instructionLabel.text = @"";
         self.d=0;
         if ([pass isEqualToString:self.passnhap]) {
            NSUserDefaults * config = [NSUserDefaults standardUserDefaults];
            [config setObject:@"FIRSTUSER" forKey:@"_key_"];
            [config setObject:pass forKey:@"_passCode_"];
            [config synchronize];
            [self dismissModalViewControllerAnimated:YES];
          
         }
         else{
            self.titleLabel.text = NSLocalizedString(@"EnterAPasscode",@"");
            self.instructionLabel.text = NSLocalizedString(@"PasscodeDidNotMatch",@"");
            [self performSelector:@selector(interface)];
        }
    }
}

@end
